<template>
    <el-container class="edit-pwd-compair-box">
        <el-header class="header-flex-box" height="80px">
            <el-row class="school-name-box">
                <el-col :span="18" class="row align-items">
                    <el-image :src="schoolLogo"></el-image>
                </el-col>
                <el-col :span="6" class="login-end-box"></el-col>
            </el-row>
        </el-header>
        <!-- 主内容区 -->
        <div class="edit-pwd-main column" :class="!footerBol ? 'edit-pwd-main2' : ''">
            <el-row class="form-flex-box">
                <el-col :span="24">
                    <div class="forget-pwd-box">
                        {{ Number(type) == 1 ? "忘记密码" : "修改密码" }}
                    </div>
                    <div class="title-font-box">
                        {{ Number(type) == 1 ? "忘记密码" : "修改密码" }}
                    </div>
                    <div class="align-center-justify">
                        <div class="step-flex-box align-items">
                            <el-steps class="mb-4" :style="Number(type) == 1 ? 'width: 100%' : 'width: 50%;'"
                                :space="200" :active="active" simple>
                                <el-step :title="item.name" v-for="(item, index) in stepsList" :key="index">
                                    <template #icon>
                                        <el-icon :class="item.icon" size="18"></el-icon>
                                    </template>
                                </el-step>
                            </el-steps>
                        </div>
                    </div>
                    <!-- 主要内容输入区 -->
                    <div class="main-input-box">
                        <div class="main-form-box" v-if="Number(type) == 1">
                            <template v-if="active == 0">
                                <el-form ref="ruleFormRef" style="width: 30rem" :model="ruleForm" :rules="rules"
                                    label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                                    <el-form-item label="手机号码" prop="phone">
                                        <el-input v-model="ruleForm.phone" placeholder="请输入手机号码" />
                                    </el-form-item>
                                    <div class="row">
                                        <el-form-item style="flex: 1;" label="验证码" prop="code">
                                            <el-input v-model="ruleForm.code"  placeholder="请输入验证码" />
                                        </el-form-item>
                                        <div style="margin-left: 15px;">
                                            <el-button type="primary" :disabled="btnDisabled"
                                                @click="handleClick">{{ Countdown }}</el-button>
                                        </div>
                                    </div>
                                </el-form>
                            </template>
                            <template v-if="active == 1">
                                <el-form ref="ruleFormRef2" style="width: 30rem" :model="ruleForm2" :rules="rules2"
                                    label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                                    <el-form-item label="新密码" prop="passwd">
                                        <el-input v-model="ruleForm2.passwd" type="password" show-password
                                            placeholder="请输入新密码" />
                                    </el-form-item>
                                    <el-form-item label="确认密码" prop="passwd2">
                                        <el-input v-model="ruleForm2.passwd2" type="password" show-password
                                            placeholder="请再次输入密码" />
                                    </el-form-item>
                                </el-form>
                            </template>
                            <template v-if="active == 2">
                                <div class="column success-flex-box">
                                    <el-icon class="iconfont icon-icon_ok"></el-icon>
                                    <label>密码已修改成功</label>
                                </div>
                            </template>
                        </div>
                        <div class="main-form-box" v-else>
                            <template v-if="active == 0">
                                <el-form ref="ruleFormRef2" style="width: 30rem" :model="ruleForm2" :rules="rules2"
                                    label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                                    <el-form-item label="原密码" prop="old_passwd">
                                        <el-input v-model="ruleForm2.old_passwd" type="password" show-password
                                            placeholder="请输入原密码" />
                                    </el-form-item>
                                    <el-form-item label="新密码" prop="passwd">
                                        <el-input v-model="ruleForm2.passwd" type="password" show-password
                                            placeholder="请输入新密码" />
                                    </el-form-item>
                                    <el-form-item label="确认密码" prop="passwd2">
                                        <el-input v-model="ruleForm2.passwd2" type="password" show-password
                                            placeholder="请再次确认密码" />
                                    </el-form-item>
                                </el-form>
                            </template>
                            <template v-if="active == 1">
                                <div class="column success-flex-box">
                                    <el-icon class="iconfont icon-icon_ok"></el-icon>
                                    <label>密码已修改成功</label>
                                </div>
                            </template>
                        </div>
                    </div>
                </el-col>
                <div class="btn-flex-box">
                    <el-button type="primary" @click="toBtn()">{{
                        active == 0 ? "下一步" : active == 1 ? "完成修改" : "去登录"
                        }}</el-button>
                </div>
            </el-row>
            <div class="footer-bottom-box" :class="footerBol ? 'footer-position-box' : ''">
                <el-icon :size="14" class="iconfont icon-icon_copyright"></el-icon>
                <label>2025</label> 东莞市第一中学(集团)市十一中学网版权所有
            </div>
        </div>
    </el-container>
</template>
<script lang="ts" setup>
import { ElMessage, type ComponentSize, type FormInstance } from "element-plus"
import schoolLogo from "../assets/images/logo.png"
import Md5 from "js-md5"
import { reactive, ref, onMounted, computed, onUnmounted } from "vue"
import { useRoute, useRouter } from "vue-router"
import {
    postChangeForgetPasswdApi,
    postCheckForgetPasswdCodeApi,
    postSendForgetPasswdCodeApi,
    putUpdatePwdApi,
} from "../components/Api/login"
import { getTime } from "../components/Api/index"
interface RuleForm {
    phone: string
    code: string
}
interface RuleForm2 {
    old_passwd: string
    passwd: string
    passwd2: string
}
const footerBol = ref<boolean>(true)
const btnDisabled = ref(false)
const second = ref<any>(null)
const timer = ref<any>(null)
const isAdmin = ref<boolean>(false)
// 类型 1忘记密码 10101 修改密码
const type = ref<any>(1)
const route = useRoute()
const router = useRouter()
const active = ref<number>(0)
const formSize = ref<ComponentSize>("large")
const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
const stepsList = ref<any[]>([])
const ruleForm = reactive<RuleForm>({
    phone: "",
    code: "",
})
const ruleForm2 = reactive<RuleForm2>({
    old_passwd: "",
    passwd: "",
    passwd2: "",
})
const uuid = ref<string>("")
const timestamp = ref<string>("")
const rules = reactive<any>({
    phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
})
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!ruleForm2.passwd && ruleForm2.passwd2) {
        callback(new Error('请输入密码'))
    } else if (value !== '' && !/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,20}$/g.test(value)) {
        callback(new Error('请输入包含英文字母大小写、数字和特殊符号的 8-20 位组合密码'))
    } else {
        callback()
    }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== ruleForm2.passwd) {
        callback(new Error('两次输入密码不一致!'))
    } else {
        callback()
    }
}
const rules2 = reactive<any>({
    old_passwd: [{ required: true, validator: validatePass, trigger: "blur" }],
    passwd: [{ required: true, validator: validatePass, trigger: 'blur' }],
    passwd2: [{ required: true, validator: validatePass2, trigger: 'blur' }],
})
const Countdown = computed(() =>
    btnDisabled.value ? `${second.value}s后重试` : "获取验证码"
)
//获取验证码
const handleClick = () => {
    //简单节流
    if (btnDisabled.value) {
        return
    }
    if (ruleForm.phone === "") {
        return ElMessage.error("请输入手机号")
    }
    getCode()
}
// 倒计时效果
const getCode = async () => {
    const params = {
        phone: ruleForm.phone,
    }
    const res: any = await postSendForgetPasswdCodeApi(params)
    if (res.code !== 1) {
        return ElMessage.error(res.message)
    }
    console.log(res.data)
    let s = 79000 //倒计时间
    if (!timer.value) {
        second.value = s
        btnDisabled.value = true
        timer.value = setInterval(() => {
            if (second.value > 0 && second.value <= s) {
                second.value--
            } else {
                btnDisabled.value = false
                clearInterval(timer.value)
                timer.value = null
            }
        }, 1000)
    }
}
// 点击登录按钮
const toBtn = async () => {
    if (Number(type.value) === 10101 && Number(active.value) === 0) {
        // 表单验证
        if (!ruleFormRef2.value) return
        ruleFormRef2.value.validate(async (valid) => {
            if (valid) {
                const params = {
                    old_passwd: Md5(ruleForm2.old_passwd),
                    passwd: Md5(ruleForm2.passwd),
                    passwd2: Md5(ruleForm2.passwd2),
                }
                const res: any = await putUpdatePwdApi(params)
                if (res.code !== 1) {
                    return ElMessage.error(res.message)
                }
                active.value += 1
            } else {
                console.log("error submit!")
            }
        })
    }
    if (Number(type.value) === 1 && Number(active.value) === 0) {
        // 表单验证
        if (!ruleFormRef.value) return
        ruleFormRef.value.validate(async (valid) => {
            if (valid) {
                const params = {
                    phone: ruleForm.phone,
                    code: ruleForm.code,
                }
                const res: any = await postCheckForgetPasswdCodeApi(params)
                if (res.code !== 1) {
                    return ElMessage.error(res.message)
                }
                uuid.value = res.data.uuid
                active.value += 1
            } else {
                console.log("error submit!")
            }
        })
    }
    if (Number(type.value) === 1 && Number(active.value) === 1) {
        // 表单验证
        console.log("进来了")
        await getTimeList()
        await toUpdPwd()
    }
    if (Number(type.value) === 1 && Number(active.value) === 2) {
        // 忘记密码
        router.replace("/login")
    }
    if (Number(type.value) === 10101 && Number(active.value) === 1) {
        // 修改密码
        // if (isAdmin.value) {
        //     router.replace("/login?source=admin")
        // } else {
        //     router.replace("/login")
        // }
        router.back()
    }
}
// 重新设定密码
const toUpdPwd = async () => {
    if (!ruleFormRef2.value) return
    ruleFormRef2.value.validate(async (valid) => {
        if (valid) {
            const key =
                ruleForm.phone +
                uuid.value +
                Md5(ruleForm2.passwd) +
                Md5(ruleForm2.passwd2) +
                timestamp.value +
                '11' +
                'hl-wlweb'
                console.log(timestamp.value,"时间戳")
            console.log(key)
            console.log(Md5(key))
            const params = {
                phone: ruleForm.phone,
                uuid: uuid.value,
                passwd: Md5(ruleForm2.passwd),
                passwd2: Md5(ruleForm2.passwd2),
                timestamp: timestamp.value,
                key: Md5(key),
            }
            const res: any = await postChangeForgetPasswdApi(params)
            if (res.code !== 1) {
                return ElMessage.error(res.msg)
            }
            active.value += 1
        } else {
            console.log("error submit!")
        }
    })
}
// 获取服务器时间
const getTimeList = async () => {
    const res: any = await getTime()
    if (res.code !== 1) {
        return false
    }
    console.log(res.data)
    timestamp.value = res.data.time
}
// 监听屏幕变化
const handleResize = () => {
    const innerHeight = window.innerHeight
    if (innerHeight < 700) {
        footerBol.value = false
    } else {
        footerBol.value = true
    }
}
onMounted(() => {
    handleResize()
    window.addEventListener("resize", handleResize, true)
    type.value = route.query.type
    if (Number(type.value) === 1) {
        stepsList.value = [
            {
                name: "手机验证",
                icon: "iconfont icon-shuzi2",
            },
            {
                name: "重置密码",
                icon: "iconfont icon-shuzi",
            },
            {
                name: "完成",
                icon: "iconfont icon-shuzi1",
            },
        ]
    } else {
        stepsList.value = [
            {
                name: "重置密码",
                icon: "iconfont icon-shuzi2",
            },
            {
                name: "完成",
                icon: "iconfont icon-shuzi",
            },
        ]
    }
    if (route.query.source === "admin") {
        isAdmin.value = true
    } else {
        isAdmin.value = false
    }
})
onUnmounted(() => {
    window.removeEventListener("resize", handleResize)
})
</script>
<style lang="scss" scoped>
.edit-pwd-compair-box {
    height: 100%;
    .header-flex-box {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;

        .school-name-box {
            width: 100%;
            display: flex;
            align-items: center;
            padding: 0 20px;
            box-sizing: border-box;
            color: #30318b;
            .el-image {
               height: 50px; 
            }
        }
    }

    .edit-pwd-main {
        height: 100%;
        background-color: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;

        .form-flex-box {
            background-color: var(--el-color-white);
            border-radius: 10px;
            width: 808px;
            height: 614px;
            margin-top: -20px;

            .forget-pwd-box {
                padding: 20px;
                box-sizing: border-box;
                border-bottom: 1px solid #eee;
                font-size: 20px;
                font-family: "Bold";
            }

            .title-font-box {
                text-align: center;
                font-size: 20px;
                font-family: Bold;
                padding-top: 40px;
            }

            .step-flex-box {
                background-color: #f5f5f5;
                width: 728px;
                height: 64px;
                border-radius: 4px;
                display: flex;
                justify-content: center;

                ::v-deep .el-steps--simple {
                    background-color: transparent;
                }
            }

            .align-center-justify {
                display: flex;
                align-items: center;
                justify-content: center;
                padding-top: 24px;
            }
        }
    }

    .edit-pwd-main2 {
        height: 100%;
    }

    .main-input-box {
        display: flex;
        justify-content: center;

        .main-form-box {
            width: 728px;
            height: 224px;
            border-radius: 4px;
            background-color: #f5f5f5;
            margin-top: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }

    .btn-flex-box {
        width: 100%;
        padding: 0 188px;
        display: flex;
        justify-content: center;

        /* 水平居中 */
        // align-items: center;
        .el-button {
            flex-grow: 1;
            /* 让按钮撑满父容器 */
            height: 40px;
        }
    }

    :deep(.el-step__head.is-process) {
        color: var(--el-color-primary);
    }

    :deep(.el-step__title.is-process) {
        color: var(--el-text-color-placeholder);
        font-weight: 10;
    }

    .success-flex-box {
        display: flex;
        justify-content: center;
        align-items: center;

        .el-icon {
            font-size: 68px;
            color: var(--el-color-primary);
        }

        label {
            color: var(--el-color-primary);
            font-family: Bold;
            margin-top: 24px;
        }
    }
}

.footer-bottom-box {
    color: #666;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    justify-content: center;
    font-size: 13px;
    font-family: "Regular";
    background-color: #F5F5F5;
    label {
        margin-left:15px;
    }
}

.footer-position-box {
    position: absolute;
    bottom: 0;
}
</style>